package JUC;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    // 6辆车抢3个停车位
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {

            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println("第\t" + Thread.currentThread().getName() +
                            "辆车争抢到停车位");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("第\t" + Thread.currentThread().getName() +
                            "辆车停车3秒后离开");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
